<?php
/**
 * User: xuanbang.wen
 * Date: 2019/9/25
 */

namespace App\Web\Model;


use App\Service\ExternalAPI\EhireApi;
use App\Web\Facades\UserAuth;
use EchoPHP\Facades\Db;
use App\Web\Model\Customer as CustomerModel;
use EchoPHP\Validator\Validator;

class CustomerAccount extends Model {
    private $tablename = 'CustomerAccount';

    /**客户联系人列表
     * @param $subid
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function show($subid) {
        $sql = 'select id as accountid,email,cname,bindehire,ehirectmid,ehireaccid,mobilephone,department,memo,isinterviewer from ' . $this->tablename . ' where subid  = ? and status = ?';
        $var = [$subid, '01'];
        $result = Db::select($sql, $var);
        $result = $this->getContactorInfo($result);
        return $result;
    }

    /**
     * 获取带是否为职位联系人的客户联系人列表（职位添加联系人时用）
     * @param $subid
     * @param $caseId
     * @return array
     */
    public function getSubContactorList($subid,$caseId) {
        $sql = 'select id as accountid,email,cname,bindehire,ehirectmid,ehireaccid,mobilephone,department,memo,isinterviewer from ' . $this->tablename . ' where subid  = ? and status = ?';
        $var = [$subid, '01'];
        $result = Db::select($sql, $var);
        $result = $this->getContactorInfo($result);
        $sql = 'select id as caseaccountid,accountid from CaseContacter where caseid = ? and subid = ? and status = ?';
        $var = [$caseId,$subid,'01'];
        $accountIdArr = Db::select($sql,$var);
        $accountIds = [];
        if (!empty($accountIdArr)) {
            foreach ($accountIdArr as $item) {
                $accountIds[$item['accountid']] = ['caseaccountid' => $item['caseaccountid'] ,'accountid' => $item['accountid']];
            }
        }
        $accountIdTmp = array_keys($accountIds);
        foreach ($result as &$item) {
            if (in_array($item['accountid'],$accountIdTmp)) {
                $item['iscasecontacter'] = 1;
                $item['caseaccountid'] = $accountIds[$item['accountid']]['caseaccountid'];
            } else {
                $item['iscasecontacter'] = 0;
                $item['caseaccountid'] = '';
            }
        }unset($item);
        return $result;
    }

    /**新增客户联系人
     * @param $params
     * @return array
     */
    public function add($params) {
        if ($params['isinterviewer']) {
            $sql = 'select count(*) as num from CustomerAccount where subid = ? and status = ? and isinterviewer = ?';
            $countNum = Db::selectOne($sql,[$params['subid'],'01',1])['num'];
            if ($countNum >= 50) {
                return [
                    'status' => false,
                    'message' => '面试官总数不可以超过50名'
                ];
            }
        }

        $sql = 'select 1 from CustomerAccount where subid = ? and mobilephone = ? and status = ?';
        $phoneExist = Db::select($sql, [$params['subid'], $params['mobilephone'], '01']);
        if ($phoneExist) {
            return [
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '号码已存在'],
            ];
        }
        $sql = 'select crmcustomerid from CustomerSub where subid = ?';
        $customerId = Db::selectOne($sql, [$params['subid']])['crmcustomerid'];
        $sql = 'insert into ' . $this->tablename . '(subid,creator,updator,email,cname,crmcustomerid,status,createdate,updatedate,mobilephone,department,memo,isinterviewer)
        value (?,?,?,?,?,?,?,NOW(),NOW(),?,?,?,?)';
        $userId = UserAuth::getLoginId();
        $var = [
            $params['subid'],
            $userId,
            $userId,
            $params['email'],
            $params['cname'],
            $customerId,
            '01',
            $params['mobilephone'],
            $params['department'],
            $params['memo'],
            $params['isinterviewer']
        ];
        $result = Db::insert($sql, $var);
        $accountId = '';
        if ($result) {
            $accountId = Db::getLastInsertId();
        }
        return [
            'status' => $result,
            'message' => $result ? '添加成功' : '添加失败',
            'accountid' => $accountId
        ];
    }

    public function addContactorDataCheck($params) {
        $rule = [
            'email|客户账户邮箱' => [
                'required', 'email'
            ],
            'cname|客户账户名称' => [
                'required', 'maxLength' => 50
            ],
            'mobilephone|面试官手机' => [
                'required','minLength' => 7, 'maxLength' => 19
            ],
            'department|部门' => [
                'maxLength' => 50
            ],
            'memo|备注' => [
                'maxLength' => 200
            ],
        ];
        $validate = new Validator($rule);
        if (!$validate->validate($params)) {
            return [
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ];
        }
        if ((preg_match('/(^(((\+)?\d{1,4}-)\d{5,15}$)|(^1\d{10}$))/', $params['mobilephone']) == 0) && (preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?(\(0\d{2,3}\)|0\d{2,3})?(\(0\d{2,3}\)|0\d{2,3})?[1-9]\d{6,7}(\-\d{1,5})?$/', $params['mobilephone']) == 0)) {
            return [
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '手机/座机格式不正确']
            ];
        }
        return [
            'status' => true,
            'message' => '校验成功'
        ];
    }

    /**修改客户联系人
     * @param $params
     * @return array
     */
    public function edit($params) {
        if ($params['isinterviewer']) {
            $sql = 'select count(*) as num from CustomerAccount where subid = ? and status = ? and isinterviewer = ?';
            $countNum = Db::selectOne($sql,[$params['subid'],'01',1])['num'];
            if ($countNum >= 50) {
                return [
                    'status' => false,
                    'message' => '面试官总数不可以超过50名'
                ];
            }
        }
        $sql = 'select 1 from ' . $this->tablename . ' where mobilephone = ? and id != ? and subid = ? and status = ?';
        $emailExist = Db::select($sql, [$params['mobilephone'], $params['accountid'], $params['subid'], '01']);
        if ($emailExist) {
            return [
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '号码已存在']
            ];
        }
        $sql = 'update ' . $this->tablename . ' set email = ?,mobilephone = ?, memo = ?, department = ? ,cname = ?, updator = ?,updatedate = NOW(),isinterviewer = ?
        where id = ?';
        $var = [
            $params['email'],
            $params['mobilephone'],
            $params['memo'],
            $params['department'],
            $params['cname'],
            UserAuth::getLoginId(),
            $params['isinterviewer'],
            $params['accountid']
        ];
        $result = Db::update($sql, $var);
        return [
            'status' => $result == 1,
            'message' => $result == 1 ? '修改成功' : '修改失败',
        ];
    }

    /**删除客户联系人
     * @param $accountId
     * @param $subId
     * @return int
     */
    public function lock($accountId, $subId) {
        $sql = 'select 1 from ' . $this->tablename . ' where id != ? and subid = ? and status = ?';
        $otherAccount = Db::select($sql, [$accountId, $subId, '01']);
        if (!$otherAccount) {
            return 0;
        }
        $sql = 'update ' . $this->tablename . ' set status = ?, updator = ?, bindehire = ?,binduid = ? ,ehireaccid = null ,ehirectmid = null,updatedate = NOW(),binddate = Now()
        where id = ? and subid = ? and status = ?';
        $var = [
            '06',
            UserAuth::getLoginId(),
            0,
            UserAuth::getLoginId(),
            $accountId,
            $subId,
            '01'
        ];
        $statement1 = Db::connect()->prepareStatement($sql, $var);
        $sql = 'update CaseContacter set status = ?, updator = ?, updatedate = Now() where accountid = ? and subid = ?';
        $var = ['06',UserAuth::getLoginId(),$accountId,$subId];
        $statement2 = Db::connect()->prepareStatement($sql, $var);
        $result = Db::connect()->prepareTransactionStatement(false, $statement1,$statement2)->execute();
        return $result ? 1 : 0;
    }

    /**绑定B端账号
     * @param $accountId
     * @param $ehireInfo
     * @return array
     */
    public function bindEhire($accountId, $ehireInfo) {
        $userId = UserAuth::getLoginId();
        $sql = 'select subid,bindehire from ' . $this->tablename . ' where id = ? and status = ?';
        $accountInfo = Db::select($sql, [$accountId, '01']);
        if ($accountInfo) {
            return [
                'status' => false,
                'message' => '客户联系人ID非法',
            ];
        }
        if ($accountInfo['bindehire'] == 0) {
            return [
                'status' => false,
                'message' => '此客户联系人已绑定网才账号',
            ];
        }
        $sql = 'select 1 from ' . $this->tablename . ' where ehireaccid = ? and subid = ? and status = ?';
        $existEhire = Db::selectOne($sql, [$ehireInfo['ehireaccid'], $accountInfo['subid'], '01']);
        if ($existEhire) {
            return [
                'status' => false,
                'message' => '此网才账号已绑定客户下另一联系人',
            ];
        }
        $sql = 'update ' . $this->tablename . ' set ehireaccid = ?, ehirectmid = ?, updator = ?, updatedate = NOW() where id = ? and status = ?';
        $var = [
            $ehireInfo['ehireaccid'],
            $ehireInfo['ehirectmid'],
            $userId,
            $accountId,
            '01'
        ];
        $result = Db::update($sql, $var);
        return [
            'status' => $result == 1,
            'message' => $result == 1 ? '绑定成功' : '绑定失败',
        ];
    }

    public function getContactorInfo($result) {
        $tmpList = [];
        //按ctmid 进行聚合
        foreach ($result as $item) {
            $tmpList[$item['ehirectmid']][] = $item['ehireaccid'];
        }
        foreach ($tmpList as &$item) {
            $item = array_unique($item);
            $item = implode(',', $item);
        }
        unset($item);
        $userInfo = [];
        $ehireApi = new EhireApi();
        //调用网才接口获取用户信息
        foreach ($tmpList as $ctmid => $hruids) {
            $where = 'hruids|' . $hruids;
            $userList = $ehireApi->getUserList2($ctmid, null, null, null, $where);
            if ($userList['code'] == '00000') {
                $userInfo = array_merge($userInfo, $userList['data']['userlist']);
            }
        }
        $userInfo = array_column($userInfo, null, 'hruid');
        foreach ($result as &$item) {
            $item['ehireemail'] = isset($userInfo[$item['ehireaccid']]['email']) ? $userInfo[$item['ehireaccid']]['email'] : '';
            $item['ehiremobile'] = isset($userInfo[$item['ehireaccid']]['mobile']) ? $userInfo[$item['ehireaccid']]['mobile'] : '';
            $item['ehirename'] = isset($userInfo[$item['ehireaccid']]['name']) ? $userInfo[$item['ehireaccid']]['name'] : '';
            $item['ehirestatus'] = isset($userInfo[$item['ehireaccid']]['activestatus']) ? $userInfo[$item['ehireaccid']]['activestatus'] : 0;
        }
        return $result;
    }

    /**
     * Notes:使用ehire接口查询crmsubid下ctm列表及用户
     * @param $subId
     * @return array
     * @throws \Exception
     */
    public function getCtmList($subId){
        $sql = 'select crmsubid from CustomerSub where subid = ?';
        $crmSubId = Db::selectOne($sql, [$subId]);
        if (!$crmSubId){
            return [];
        }
        $ehireApi = new EhireApi();
        $userList = $ehireApi->getUserListByAccsubid($crmSubId['crmsubid']);
        return $userList['data']['ctmlist'] ?? [];
    }
}